<script setup lang="ts">
import { MenuForm, MenuVO } from "@/api/menu/types";
import { listMenusManager, addMenu, deleteMenu, moveMenu } from "@/api/menu";
import { MenuTypeEnum } from "@/enums/MenuTypeEnum";
import SvgIcon from "@/components/SvgIcon/index.vue";
import IconSelect from "@/components/IconSelect/index.vue";
import { useDictionary } from "@/utils/useTable";
import { useDictStoreHook } from "@/store/modules/dictionary"; // 引入
const dictionaryStore = useDictStoreHook(); // 定义

defineOptions({
  name: "SYSTEMMENU",
  inheritAttrs: false,
});

const menuFormRef = ref(ElForm);

const loading = ref(false);
const dialog = reactive<DialogOption>({
  visible: false,
});

const menuList = ref<MenuVO[]>([]);

const menuOptions = ref<OptionType[]>([]);

const applicationTypeList = ref(useDictionary("ApplicationType"));
const formData = reactive<MenuForm>({
  parentId: "0",
  sort: 1,
  permissionCode: "",
  permissionName: "",
  permissionType: MenuTypeEnum.CATALOG,
  icon: "",
  applicationType: "",
  pageTarget: "0",
});

watch(
  () => formData.permissionType,
  (newVal) => {
    if (newVal === MenuTypeEnum.EXTLINK) {
      formData.pageTarget = "1";
    } else {
      formData.pageTarget = "0";
    }
  }
);
const rules = reactive({
  parentId: [{ required: true, message: "请选择顶级菜单", trigger: "change" }],
  permissionName: [
    { required: true, message: "请输入权限名称", trigger: "blur" },
    { max: 45, message: "权限名称不能超过45个字符", trigger: "blur" },
  ],
  permissionType: [
    { required: true, message: "请选择权限类型", trigger: "change" },
  ],
  permissionCode: [
    { required: true, message: "请输入权限编码", trigger: "blur" },
    { max: 45, message: "权限编码不能超过45个字符", trigger: "blur" },
  ],
  url: [
    { required: true, message: "请输入权限路径", trigger: "blur" },
    { max: 250, message: "url不能超过250个字符", trigger: "blur" },
  ],
});

// 选择表格的行菜单ID
const selectedRowMenuId = ref<number | undefined>();

const menuCacheData = reactive({
  permissionType: "",
  url: "",
});

/**
 * 查询
 */
function handleQuery() {
  // 重置父组件
  loading.value = true;
  listMenusManager()
    .then(({ data }) => {
      menuList.value = data;
      selectMenuList.value = data;
      menuOptions.value = [
        { id: "0", permissionName: "顶级菜单", children: selectMenuList.value },
      ];
    })
    .then(() => {
      loading.value = false;
    });
}

/**行点击事件 */
function onRowClick(row: MenuVO) {
  selectedRowMenuId.value = row.id;
}

/**
 * 打开表单弹窗
 *
 * @param parentId 父菜单ID
 * @param menuId 菜单ID
 */
function openDialog(parentId?: string, menuId?: number, data?: any) {
  dialog.visible = true;
  if (menuId) {
    dialog.title = "编辑权限";
    Object.assign(formData, data);
    formData.permissionType = formData.permissionType?.toString();
    formData.pageTarget =
      formData.permissionType === MenuTypeEnum.EXTLINK
        ? "1"
        : formData.pageTarget ?? "0";
    menuCacheData.permissionType = data.permissionType;
    menuCacheData.url = data.url ?? "";
  } else {
    dialog.title = "新增权限";
    formData.parentId = parentId;
    // 新增时，把parent的applicationType，携带给子元素
    if (formData.parentId !== "0") {
      formData.applicationType = data.applicationType;
    }
    // 默认权限按钮类型赋值
    formData.permissionType =
      data?.permissionType == MenuTypeEnum.CATALOG
        ? MenuTypeEnum.CATALOG
        : data?.permissionType == MenuTypeEnum.MENU
        ? MenuTypeEnum.MENU
        : data?.permissionType == MenuTypeEnum.BUTTON
        ? MenuTypeEnum.BUTTON
        : MenuTypeEnum.EXTLINK;
  }
}

/** 权限类型切换事件处理 */
function onMenuTypeChange() {
  // 如果权限类型改变，清空权限路径；未改变在切换后还原权限路径
  if (formData.permissionType !== menuCacheData.permissionType) {
    formData.url = "";
  } else {
    formData.url = menuCacheData.url;
  }
}

const postLoading = ref(false);
/** 菜单保存提交 */
function submitForm() {
  menuFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      postLoading.value = true;
      const text = formData.id ? "修改" : "新建";
      const data = {
        ...formData,
        permissionType: Number(formData.permissionType),
        applicationType: formData.applicationType || "web",
      };
      addMenu(data)
        .then(async () => {
          ElMessage.success(`${text}成功`);
          closeDialog();
          handleQuery();
          // location.reload();
        })
        .finally(() => {
          postLoading.value = false;
        });
    }
  });
}

// 移动相关操作
const moveDialog = reactive<DialogOption>({
  visible: false,
  title: "权限移动",
  posting: false,
  id: "",
  parentId: "",
});

interface PermRow {
  id?: string;
  permissionName?: string;
  children?: any;
}

const moveMenuList = ref();
// 深层拷贝
function deepCopy(val: any) {
  return JSON.parse(JSON.stringify(val));
}
const gindex: any = ref([]);
function removeDuplicate(current: any) {
  current.forEach((val: any, i: PermRow) => {
    if (gindex.value.indexOf(val.id) == -1) {
      gindex.value.push(val.id);
    } else {
      current.splice(i, 1);
    }

    if (val.children) {
      val.children = removeDuplicate(val.children);
    }
  });
  return current;
}
// 移动处理
function handleRemove(row: PermRow) {
  gindex.value = [row.id];
  let splitMenuList = deepCopy(selectMenuList.value);
  const list = removeDuplicate(splitMenuList);
  moveMenuList.value = [
    { id: "0", permissionName: "顶级菜单", children: list },
  ];

  moveDialog.visible = true;
  moveDialog.id = row.id;
  moveDialog.title = `【${row.permissionName}】权限移动`;
}

function handleTreeData({ id }: any) {
  moveDialog.parentId = id;
}

function submitRemove() {
  const { id, parentId } = moveDialog;
  if (!parentId) return false;
  moveDialog.posting = true;
  moveMenu({ id, parentId })
    .then(async () => {
      ElMessage.success(`移动成功`);
      closeMoveDialog();
      // location.reload();
      handleQuery();
    })
    .finally(() => {
      closeMoveDialog();
    });
}

/** 关闭弹窗 */
function closeMoveDialog() {
  moveDialog.posting = false;
  moveDialog.visible = false;
  moveDialog.id = "";
  moveDialog.parentId = "";
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/** 重置表单 */
function resetForm() {
  menuFormRef.value.resetFields();
  menuFormRef.value.clearValidate();

  formData.id = undefined;
  formData.parentId = "";
  formData.visible = 1;
  formData.sort = 1;
  formData.perm = undefined;
  formData.permissionName = "";
  formData.permissionCode = "";
  formData.applicationType = "";
  formData.icon = "";
  formData.permissionType = undefined;
  formData.url = undefined;
  formData.redirect = undefined;
  formData.alwaysShow = undefined;
  formData.keepAlive = undefined;
  formData.enabled = 1;
}

/** 下拉菜单数据处理 */
let selectMenuList = ref<any>([]);

const ids = ref<number[]>([]);
/** 删除菜单 */
function handleDelete(menuId?: number) {
  const menuIds = [menuId || ids.value].join(",");
  if (!menuIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      const idsArr = menuIds.split(",");
      const data = {
        ids: idsArr,
      };
      deleteMenu(data).then(() => {
        ElMessage.success("删除成功");
        // location.reload();
        handleQuery();
      });
    })
    .catch(() => ElMessage.info("已取消删除"));
}
/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

async function initParam() {
  handleQuery();
}

const defaultProps = {
  children: "children",
  label: "permissionName",
  value: "id",
};
onMounted(() => {
  initParam();
});
</script>

<template>
  <div class="app-container">
    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" plain @click="openDialog('0')">
          <i-ep-plus />
          新增</el-button
        >
      </template>

      <div class="draggable">
        <el-table
          v-loading="loading"
          :data="menuList"
          highlight-current-row
          border
          row-key="id"
          @row-click="onRowClick"
          @selection-change="handleSelectionChange"
          :tree-props="{
            children: 'children',
            hasChildren: 'hasChildren',
          }"
        >
          <!-- <el-table-column type="selection" width="55" align="center" /> -->
          <el-table-column label="权限名称" min-width="180">
            <template #default="scope">
              <svg-icon :icon-class="scope.row.icon" class="mr-[3px]" />
              {{ scope.row.permissionName }}
            </template>
          </el-table-column>

          <el-table-column label="类型" align="center" width="100">
            <template #default="scope">
              <el-tag
                v-if="scope.row.permissionType == MenuTypeEnum.CATALOG"
                type="warning"
                >目录</el-tag
              >
              <el-tag
                v-if="
                  scope.row.permissionType == MenuTypeEnum.MENU &&
                  scope.row.showType !== 2
                "
                type="success"
                >菜单</el-tag
              >
              <el-tag
                v-if="
                  scope.row.permissionType == MenuTypeEnum.MENU &&
                  scope.row.showType === 2
                "
                >普通页面</el-tag
              >
              <el-tag
                v-if="scope.row.permissionType == MenuTypeEnum.BUTTON"
                type="danger"
                >按钮</el-tag
              >
              <el-tag
                v-if="
                  scope.row.permissionType == MenuTypeEnum.EXTLINK &&
                  scope.row.showType === 2
                "
                type="info"
                >外链页面</el-tag
              >
              <el-tag
                v-if="
                  scope.row.permissionType == MenuTypeEnum.EXTLINK &&
                  scope.row.showType != 2
                "
                type="info"
                >外链菜单</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column label="是否启用" align="center" width="100">
            <template #default="scope">
              <el-tag v-if="scope.row.enabled == 0" type="warning">停用</el-tag>
              <el-tag v-if="scope.row.enabled == 1" type="success">启用</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            label="权限路径"
            align="left"
            prop="url"
            show-overflow-tooltip
          />

          <el-table-column
            label="权限编码"
            align="center"
            prop="permissionCode"
            show-overflow-tooltip
          />

          <el-table-column label="排序" align="center" width="80" prop="sort" />

          <el-table-column label="应用类型" align="center" width="100">
            <template #default="scope">
              <el-tag>{{
                dictionaryStore.filterDictName(
                  "ApplicationType",
                  scope.row.applicationType
                ) ||
                scope.row.applicationType ||
                "web"
              }}</el-tag>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            align="center"
            label="操作"
            width="300"
          >
            <template #default="scope">
              <el-button
                v-if="scope.row.permissionType != MenuTypeEnum.BUTTON"
                type="primary"
                link
                size="small"
                @click.stop="openDialog(scope.row.id, undefined, scope.row)"
              >
                <i-ep-plus />新增
              </el-button>

              <el-button
                type="primary"
                link
                size="small"
                @click.stop="openDialog(undefined, scope.row.id, scope.row)"
              >
                <i-ep-edit />编辑
              </el-button>
              <el-button
                type="primary"
                link
                size="small"
                @click.stop="handleDelete(scope.row.id)"
                ><i-ep-delete />
                删除
              </el-button>
              <el-button
                type="primary"
                link
                size="small"
                @click.stop="handleRemove(scope.row)"
                ><i-ep-rank />
                移动
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <el-dialog
      :close-on-click-modal="false"
      v-model="dialog.visible"
      :title="dialog.title"
      :destroy-on-close="true"
      append-to-body
      width="650px"
      @close="closeDialog"
    >
      <el-form
        ref="menuFormRef"
        :model="formData"
        :rules="rules"
        label-width="160px"
      >
        <el-form-item
          v-if="
            !(formData.id && formData.permissionType === MenuTypeEnum.BUTTON)
          "
          label="父级菜单"
          prop="parentId"
        >
          <el-tree-select
            v-model="formData.parentId"
            placeholder="选择上级菜单"
            :data="menuOptions"
            filterable
            check-strictly
            :render-after-expand="false"
            :props="defaultProps"
          />
        </el-form-item>

        <el-form-item label="权限名称" prop="permissionName">
          <el-input
            v-model="formData.permissionName"
            placeholder="请输入权限名称"
          />
        </el-form-item>

        <!-- 所属应用 -->
        <!-- :disabled="formData.parentId !== '0'" <el-option label="web" value="web" />-->
        <el-form-item label="应用类型">
          <el-select
            v-model="formData.applicationType"
            clearable
            :disabled="formData.parentId !== '0'"
          >
            <el-option
              v-for="item in applicationTypeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="权限类型" prop="permissionType">
          <el-radio-group
            v-model="formData.permissionType"
            @change="onMenuTypeChange"
          >
            <el-radio label="0">目录</el-radio>
            <el-radio label="1">菜单</el-radio>
            <el-radio label="2">按钮</el-radio>
            <el-radio label="3">外链</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item
          v-if="formData.permissionType == MenuTypeEnum.EXTLINK"
          label="外链地址"
          prop="url"
        >
          <el-input v-model="formData.url" placeholder="请输入外链完整路径" />
        </el-form-item>

        <!-- 目录路径 -->
        <el-form-item
          v-if="formData.permissionType == MenuTypeEnum.CATALOG"
          label="权限路径"
          prop="url"
        >
          <el-input
            v-if="formData.permissionType == MenuTypeEnum.CATALOG"
            v-model="formData.url"
            placeholder="system"
          />
          <el-input v-else v-model="formData.url" placeholder="user" />
        </el-form-item>

        <!-- url路径/组件路径 -->
        <el-form-item
          v-if="
            formData.permissionType == MenuTypeEnum.MENU &&
            formData.applicationType !== 'app'
          "
          label="页面路径"
          prop="url"
        >
          <el-input
            v-model="formData.url"
            placeholder="system/user"
            style="width: 95%"
          >
            <template
              v-if="formData.permissionType == MenuTypeEnum.MENU"
              #prepend
              >src/views/</template
            >
            <template
              v-if="formData.permissionType == MenuTypeEnum.MENU"
              #append
              >/index.vue</template
            >
          </el-input>
        </el-form-item>

        <!-- url路径/组件路径 -->
        <el-form-item
          v-if="
            formData.permissionType == MenuTypeEnum.MENU &&
            formData.applicationType === 'app'
          "
          label="页面路径"
          prop="url"
        >
          <el-input
            v-model="formData.url"
            placeholder="system/user"
            style="width: 95%"
          >
            <template
              v-if="formData.permissionType == MenuTypeEnum.MENU"
              #prepend
              >pages/</template
            >
            <template
              v-if="formData.permissionType == MenuTypeEnum.MENU"
              #append
              >.vue</template
            >
          </el-input>
        </el-form-item>

        <!-- 展示方式 -->
        <el-form-item
          label="展示方式"
          v-if="
            formData.permissionType == MenuTypeEnum.MENU ||
            formData.permissionType == MenuTypeEnum.EXTLINK
          "
        >
          <el-radio-group v-model="formData.showType">
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">普通页面</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 是否当前页跳转 -->
        <el-form-item
          label="页面打开方式"
          v-if="
            formData.permissionType == MenuTypeEnum.MENU ||
            formData.permissionType == MenuTypeEnum.EXTLINK
          "
        >
          <el-select
            v-model="formData.pageTarget"
            clearable
            :disabled="formData.permissionType == MenuTypeEnum.EXTLINK"
          >
            <el-option label="工作区" value="0" />
            <el-option label="新窗口" value="1" />
          </el-select>
        </el-form-item>

        <!-- 排序 -->
        <el-form-item label="排序" prop="sort">
          <el-input-number
            v-model="formData.sort"
            style="width: 100px"
            controls-position="right"
            :min="0"
          />
        </el-form-item>

        <!-- 权限编码 -->
        <el-form-item label="权限编码" prop="permissionCode">
          <el-input
            v-model="formData.permissionCode"
            placeholder="sys:user:add"
          />
        </el-form-item>

        <!-- 权限编码 -->
        <el-form-item
          v-if="formData.permissionType != MenuTypeEnum.BUTTON"
          label="图标"
          prop="icon"
        >
          <icon-select v-model="formData.icon" />
        </el-form-item>
        <el-form-item label="是否启用" prop="enabled">
          <el-radio-group v-model="formData.enabled">
            <el-radio :label="0">停用</el-radio>
            <el-radio :label="1">启用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="postLoading" type="primary" @click="submitForm"
            >确 定</el-button
          >
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 权限移动采用虚拟树形展示 -->
    <el-dialog
      :close-on-click-modal="false"
      v-model="moveDialog.visible"
      :title="moveDialog.title"
      :destroy-on-close="true"
      append-to-body
      width="550px"
      draggable
      @close="closeMoveDialog"
    >
      <el-tree-v2
        :data="moveMenuList"
        :height="300"
        check-strictly
        :item-size="36"
        :indent="30"
        :default-expanded-keys="['0']"
        :props="defaultProps"
        @node-click="handleTreeData"
      />
      <template #footer>
        <div class="dialog-footer">
          <el-button
            :loading="moveDialog.posting"
            type="primary"
            @click="submitRemove"
            >移 动</el-button
          >
          <el-button @click="closeMoveDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped></style>
